package com.zzy.accessdecision.accessDecision;

import com.zzy.accessdecision.mapper.ResourceMapper;
import com.zzy.accessdecision.pojo.Resource;
import com.zzy.accessdecision.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;

/**
 * @author Lucas-zhang
 * @description TODO
 * @date 2022-03-25 10:05
 */
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    @Autowired
    private ResourceMapper resourceMapper;

    // Ant风格匹配器
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    /**
     * 获取当前请求所需要的权限
     * @param object
     * @return
     * @throws IllegalArgumentException
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        FilterInvocation request = (FilterInvocation) object;
        String url = request.getRequestUrl();

        // 获取所有的资源与对应角色信息
        List<Resource> resources = resourceMapper.getAllResourceWithRole();

        // 遍历所有的资源，查找与当前请求匹配的url
        for (Resource resource : resources) {
            // 匹配上
            if (antPathMatcher.match(resource.getUrl(), url)) {
                // 获取url对应的角色信息
                List<Role> roles = resource.getRoleList();
                String[] roleStr = new String[roles.size()];
                // 遍历roles集合，将每一个角色信息转为字符串形式
                for (int i = 0; i < roleStr.length; i++) {
                    roleStr[i] = roles.get(i).getName();
                }

                // 返回所有的角色信息
                return SecurityConfig.createList(roleStr);
            }
        }

        // 如果没有匹配上的，就返回一个自定义的作为个标记，只要是ROLE_null则说明不匹配
        return SecurityConfig.createList("ROLE_null");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    /**
     * 校验类是否支持
     * @param clazz
     * @return
     */
    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
